package com.xue.util;


import java.util.concurrent.TimeUnit;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class RedisLock {
	
//	private Logger log = LoggerFactory.getLogger(RedisLock.class);
	
	@Autowired
    private StringRedisTemplate stringRedisTemplate;
	
	/**
     * 加锁
     * @param key
     * @param value 当前时间+超时时间
     * @return
     */
    public boolean lock(String key, String value) { 
    	Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, value);
        Long surplusTime = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
       
    	if (aBoolean) {
    		stringRedisTemplate.expire(key, Long.parseLong(value), TimeUnit.SECONDS);//暂设置为80s过期，防止异常中断锁未释放
    		//log.info("该线程【{}】加锁成功,该key【{}】剩余过期时间【{}】秒", value, key, surplusTime);
            return true;
        }
    //	log.info("该线程【{}】加锁失败,该key【{}】剩余过期时间【{}】秒", value, key, surplusTime);
        return false;
    }
    /**
     * 	加锁
     * @param key
     * @param value 当前时间+超时时间
     * @return
     */
    public boolean lockMap(String key , String value) {
//    	if (stringRedisTemplate.opsForHash().setIfAbsent(key, value)) {
//            return true;
//        }
    	return false;
    }

    /**
     * 解锁
     * @param key
     * @param value
     * @return
     */
    public boolean unlock(String key, String value) {
        String currentVaule = stringRedisTemplate.opsForValue().get(key);
        try {
            if (!StringUtils.isEmpty(currentVaule) && currentVaule.equals(value)) {
                stringRedisTemplate.opsForValue().getOperations().delete(key);
                return true;
            }
        } catch (Exception e) {
           // log.error("【redis分布式锁】解锁异常，{}" , e);
        }
        return false;
    }
}
